/*
 * IfNode.cpp
 *
 *  Created on: 28/dic/2010
 *      Author: computer
 */

#include "DerivationTree.h"
#include "IfInstruction.h"
#include "ElseBlockInstruction.h"

ElseNode::ElseNode() : NodeTree_CRTP<ElseNode>() { }

ElseNode::ElseNode(const ElseNode& copy) : NodeTree_CRTP<ElseNode>(copy), endElse(copy.endElse), listElse(copy.listElse) { }

void ElseNode::setEndElse(const AutoPointer<NodeTree>& _endElse) {
	endElse = _endElse;
}

void ElseNode::addElse(const AutoPointer<NodeTree>& _else) {
	listElse.push_back(_else);
}

bool ElseNode::execute(Pointer<LeonardVirtualMachine> LVM) {
	TreeExpression::ElseBlockInstruction* ris = new TreeExpression::ElseBlockInstruction();
	std::list< AutoPointer<NodeTree> >::reverse_iterator j;
	for (j = listElse.rbegin(); j != listElse.rend(); ++j) {//TODO why reverse?
		(*j)->execute(LVM);//Load the if block
		ris->addElseBlock(LVM->top());
		LVM->pop();
	}
	if (!endElse.isNull()) {
		endElse->execute(LVM);
		ris->setEndElseBlock(LVM->top());//set the condition
		LVM->pop();
	}
	LVM->push(AutoPointer<TreeExpression::Expression>(ris));
	return true;
}
